package com.suql.kotlin.activity

import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.support.v4.content.ContextCompat
import android.widget.Toast
import java.security.Permission
import java.util.jar.Manifest

/**
 * @ClassName: BaseActivity
 * @Dscription: Activity基类
 * @Author: su qinglin
 * @Date: 2018/7/26 16:59
 */
open class BaseActivity : Activity() {

    var permissionCallback: PermissionCallback? = null

    fun Activity.showToast(msg: String) {

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    fun checkPermission(callback: PermissionCallback) {

        permissionCallback = callback
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!!, 100)
            } else {
                permissionCallback?.onGranted()
            }
        }
    }

    fun checkPermission() {

        permissionCallback = null
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!!, 100)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100) {

            if (grantResults?.size!! > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                permissionCallback?.onGranted()
            } else {
                showToast("请授权")
            }
        }
    }

    interface PermissionCallback {
        open fun onGranted()
    }
}
